<!--
 @description 跳转关联类目内容
 @fileName RelateCategoy.vue
 @author zengqiongying
 @created 2022/12/06 20:22:01
-->
<template>
  <div class="relate-category">
    <div class="relate-item">
      <el-select v-model="formData.gotoType" style="width:100%" clearable @change="handleChangeType">
        <el-option
          v-for="(o,i) in gotoTypeList"
          :key="i"
          :value="o.dictCode"
          :label="o.dictName"
        />
      </el-select>
    </div>
    <div class="relate-item" :class="{'clo-16':formData.gotoType !== 'GOODS_CENTER_CATEGORY'}">
      <template v-if="formData.gotoType === 'GOODS_CENTER_CATEGORY'">
        <el-cascader
          v-model="categoryIdPaths"
          placeholder="请选择类目"
          :options="categoryTreeList"
          filterable
          :props="{
            checkStrictly: false,
            multiple:true,
            emitPath:false,
            value:'categoryId',
            label:'categoryName',
            children:'childList'
          }"
          style="width:100%"
          size="mini"
          clearable
          collapse-tags
          @change="handleCategoryChange"
        />
      </template>
      <template v-if="formData.gotoType === 'OUTSIDE_LINK'">
        <el-input v-model="formData.gotoValue" placeholder="请输入外部链接" maxlength="150" />
      </template>
      <template v-if="formData.gotoType === 'APPLY_PAGE'">
        <el-select v-model="formData.gotoValue" @change="handlePageChange">
          <el-option v-for="(o,i) in appPageList" :key="i" :label="o.pageName" :value="o.pageUrl" />
        </el-select>
      </template>
      <template v-if="formData.gotoType === 'ATLAS' && !hideAtlasChild">
        <!-- <el-select v-model="formData.gotoValue" @change="handleAtlasChange">
          <el-option v-for="(o,i) in atlasPicList" :key="i" :label="o.atlasName" :value="o.id" />
        </el-select> -->
        <el-cascader
          v-model="selectedAtlasValue"
          :options="atlasPicList"
          :props="{ checkStrictly: true,value:'id',label:'atlasName',children:'next' }"
          clearable
          filterable
          size="mini"
          style="width:100%"
          @change="handleAtlasChange"
        />
      </template>
      <template v-if="['HELP_CENTER_DETAIL','CUSTOM_PAGE','GOODS_CENTER_DETAIL','CUSTOMIZED_NEW_PRODUCT_SERIES','DEFINE_TAB','PRODUCT_COMBINATION'].includes(formData.gotoType)">
        <el-input v-model="formData.gotoName" placeholder="请选择" @focus="openDialog(formData.gotoType)">
          <i slot="suffix" class="el-input__icon el-icon-search" @click.self="openDialog(formData.gotoType)" />
        </el-input>
      </template>
      <template v-if="formData.gotoType==='SCHEME_CENTER'">
        <el-input v-model="formData.gotoName" placeholder="请配置范围" @focus="openDialog(formData.gotoType)">
          <i slot="suffix" class="el-input__icon el-icon-search" @click.self="openDialog(formData.gotoType)" />
        </el-input>
      </template>
      <template v-if="formData.gotoType==='SCHEME_CUSTOMIZATION'">
        <el-input v-model="formData.gotoName" placeholder="请配置定制产品范围" @focus="openDialog(formData.gotoType)">
          <i slot="suffix" class="el-input__icon el-icon-search" @click.self="openDialog(formData.gotoType)" />
        </el-input>
      </template>
    </div>
    <div v-if="formData.gotoType === 'GOODS_CENTER_CATEGORY'" class="relate-item">
      <el-select v-model="formData.filterId" style="width:100%">
        <el-option
          v-for="(o,i) in goodsTemplateList"
          :key="i"
          :value="o.id"
          :label="o.name"
        />
      </el-select>
    </div>
    <component
      :is="dlgComponentName"
      v-if="visibleDlg"
      :visible.sync="visibleDlg"
      :selected-id="formData.gotoValue"
      @change="dlgSelectSuccess"
    />
  </div>
</template>

<script>
import { getCategoryTree, getAppPageList, filterTemplatePage } from '@/api/shopauxPlat/navConfig'
import { searchAtlas } from '@/api/shopauxPlat/atlasManagement'
import HelpList from './HelpList'
import GoodsList from './GoodsList'
import CustomPageList from './CustomPageList'
import CustomizedNewProductSeriesList from './CustomizedNewProductSeriesList'
import DefineTabList from './DefineTabList'
import SchemeRangeConfig from './SchemeRangeConfig'
import ProductCombinationList from './ProductCombinationList'
import CustomizationRangeConfig from './CustomizationRangeConfig'
export default {
  name: 'HomeFloorRelateCategory',
  components: {
    HelpList,
    GoodsList,
    CustomPageList,
    CustomizedNewProductSeriesList,
    DefineTabList,
    SchemeRangeConfig,
    ProductCombinationList,
    CustomizationRangeConfig
  },
  props: {
    value: {
      type: Object,
      default: () => ({})
    },
    includes: {
      type: Array,
      default: () => []
    },
    hideAtlasChild: {
      // 是否隐藏图册子级选择
      type: Boolean,
      default: false
    }
  },
  data() {
    return {
      gotoTypeList: [
        { dictId: '02', dictName: '外部链接', dictCode: 'OUTSIDE_LINK' },
        { dictId: '01', dictName: '商品中心类目', dictCode: 'GOODS_CENTER_CATEGORY' },
        { dictId: '03', dictName: '应用页面', dictCode: 'APPLY_PAGE' },
        { dictId: '04', dictName: '图册', dictCode: 'ATLAS' },
        { dictId: '05', dictName: '帮助中心', dictCode: 'HELP_CENTER' },
        // 以下待确定
        { dictId: '06', dictName: '帮助中心详情', dictCode: 'HELP_CENTER_DETAIL' },
        { dictId: '07', dictName: '自定义页面', dictCode: 'CUSTOM_PAGE' },
        { dictId: '08', dictName: '商品详情', dictCode: 'GOODS_CENTER_DETAIL' },
        { dictId: '09', dictName: '商品分类', dictCode: 'GOODS_CATE' },
        { dictId: '09', dictName: '定制新品系列', dictCode: 'CUSTOMIZED_NEW_PRODUCT_SERIES' },
        { dictId: '10', dictName: '自定义导航', dictCode: 'DEFINE_TAB' },
        { dictId: '11', dictName: '方案中心', dictCode: 'SCHEME_CENTER' },
        { dictId: '12', dictName: '搭配套餐', dictCode: 'PRODUCT_COMBINATION' },
        { dictId: '13', dictName: '定制产品', dictCode: 'SCHEME_CUSTOMIZATION' }
      ],
      formData: {
        gotoType: '', // 关联类型
        categoryDTOList: [], // 类目ID
        filterId: '', // 商品中心类目模板
        gotoValue: '', // 关联内容
        gotoName: '' // 内容名称(帮助中心详情，自定义页面，商品详情)
      },
      categoryIdPaths: [], // 当前所选商品中心类目id集合
      categoryTreeList: [], // 商品中心类目集合
      goodsTemplateList: [], // 商品类目模板集合
      appPageList: [], // 应用页面
      atlasPicList: [], // 图册图片集合
      visibleDlg: false,
      dlgComponentName: '',
      selectedAtlasValue: [] // 当前所选图册
    }
  },
  computed: {
    lastCategoryList() {
      const list = this.getCategoryLastNode(this.categoryTreeList)
      return list
    }
  },
  watch: {
    formData: {
      handler(v) {
        this.$emit('input', v)
      },
      deep: true,
      immediate: true
    },
    'formData.gotoType'(v) {
      /* for (const k in this.formData) {
        if (k !== 'gotoType') {
          this.$set(this.formData, k, '')
        }
      }
      this.categoryIdPaths = [] */
    },
    value: {
      handler(v) {
        this.initFormData(v)
      },
      deep: true,
      immediate: true
    }
    /* selectedAtlasValue(v) {
      if (this.formData.gotoType === 'ATLAS') {
        this.formData.gotoValue = v.join(',')
        this.setAtlasNames(v)
      }
    } */
  },
  created() {
    if (this.includes && this.includes.length > 0) {
      this.gotoTypeList = this.gotoTypeList.filter(v => {
        return this.includes.includes(v.dictCode)
      })
    }
    this.getBasicData()
  },
  activated() {},

  mounted() {},

  methods: {
    initFormData(v) {
      for (const k in this.formData) {
        const val = v[k] ? v[k] : k === 'categoryDTOList' ? [] : ''
        if (k === 'categoryDTOList') {
          this.categoryIdPaths = val.map(v => v.categoryId)
        }
        this.$set(this.formData, k, val)
      }
      if (this.formData.gotoType === 'ATLAS') {
        this.selectedAtlasValue = this.formData.gotoValue.split('|')
      }
    },
    getBasicData() {
      getCategoryTree().then(res => {
        if (res.success === 1) {
          this.categoryTreeList = res.data || []
        }
      })
      // 应用页面
      getAppPageList().then(res => {
        if (res.success === 1) {
          this.appPageList = res.data || []
          if (this.value.gotoValue) {
            const obj = this.appPageList.find(v => v.pageUrl === this.value.gotoValue)
            if (obj && obj.pageName) {
              this.$set(this.formData, 'gotoName', obj.pageName)
            }
          }
        }
      })
      // 图册
      const atlFormData = new FormData()
      atlFormData.append('pageFlag', false)
      atlFormData.append('filtersRaw', [])
      searchAtlas(atlFormData).then(res => {
        if (res.success === 1) {
          this.atlasPicList = res.data ? res.data.records || [] : []
        }
      })
      // 筛选模板
      filterTemplatePage().then(res => {
        if (res.success === 1) {
          this.goodsTemplateList = res.data ? res.data.records || [] : []
        }
      })
    },
    handleChangeType() {
      for (const k in this.formData) {
        if (k !== 'gotoType') {
          this.$set(this.formData, k, '')
        }
      }
      this.categoryIdPaths = []
    },
    handlePageChange(val) {
      const obj = this.appPageList.find(v => v.pageUrl === val)
      this.formData.gotoName = (obj && obj.pageName) || ''
    },
    // 图册选择切换
    handleAtlasChange(ids) {
      const names = []
      if (ids.length > 0) {
        const first = this.getAtlasNode(this.atlasPicList, ids[0])
        if (first && first.atlasName) {
          names.push(first.atlasName)
        }
        if (ids.length > 1 && first.next && first.next.length > 0) {
          const second = this.getAtlasNode(first.next, ids[1])
          if (second && second.atlasName) {
            names.push(second.atlasName)
          }
          if (ids.length > 2 && second.next && second.next.length > 0) {
            const third = this.getAtlasNode(second.next, ids[2])
            if (third && third.atlasName) {
              names.push(third.atlasName)
            }
          }
        }
      }
      this.formData.gotoName = names.join('/')
      this.formData.gotoValue = ids.join('|')
    },
    getAtlasNode(list, id) {
      return list.find(v => v.id === id)
    },
    // 品类选择变更 el-cascader 为false时
    handleCategoryChange(ids) {
      const lastCategoryList = [] // 所选末级分类集合
      ids.forEach(id => {
        const node = this.lastCategoryList.find(v => v.categoryId === id)
        if (node && node.categoryId) {
          lastCategoryList.push(node)
        }
      })
      // this.$emit('category-change', lastCategoryList)
      this.$set(this.formData, 'categoryDTOList', lastCategoryList)
    },
    // el-cascader 属性设置为emitPath=true时使用
    handleCategoryEmitPathChange(pathIds) {
      const tree = this.categoryTreeList
      const lastCategoryList = [] // 所选末级分类集合
      pathIds.forEach(ids => {
        const id = ids[0]
        const item = tree.find(v => v.categoryId === id)
        if (item) {
          if (ids.length > 1 && item.childList && item.childList.length > 0) {
            const tempId = [...ids]
            tempId.splice(0, 1)
            const child = this.getLastTreeNode(tempId, item.childList)
            if (child && child.categoryId) {
              lastCategoryList.push(child)
            }
          } else {
            lastCategoryList.push({
              categoryId: item.categoryId,
              categoryName: item.categoryName
            })
          }
        }
      })
      // this.$emit('category-change', lastCategoryList)
      this.$set(this.formData, 'categoryDTOList', lastCategoryList)
    },
    /**
     * 获取指定树节点下末级节点中的置顶节点
     * @param {Array} ids 节点ID路径
     * @param {Array} tree 指定树形节点
     * @returns {Object} 符合ids最末级id的末级节点
     * **/
    getLastTreeNode(ids, tree) {
      let node = null
      for (const id of ids) {
        const item = tree.find(v => v.categoryId === id)
        if (item) {
          if (item.childList && item.childList.length) {
            tree = item.childList
          } else {
            node = {
              categoryId: item.categoryId,
              categoryName: item.categoryName
            }
            break
          }
        } else {
          break
        }
      }
      return node
    },
    // 获取树形类目的所有末级类目
    getCategoryLastNode(data) {
      const result = []
      data.forEach(item => { // 遍历树
        const loop = data => {
          const child = data.childList
          if (child && child.length) { // 是否有子节点，有则继续遍历下一级，无则是叶子节点
            for (let i = 0; i < child.length; i++) {
              loop(child[i])
            }
          } else {
            result.push(data)
          }
        }
        loop(item)
      })

      return result
    },
    openDialog(type) {
      const com = {
        'HELP_CENTER_DETAIL': 'HelpList',
        'GOODS_CENTER_DETAIL': 'GoodsList',
        'CUSTOM_PAGE': 'CustomPageList',
        'CUSTOMIZED_NEW_PRODUCT_SERIES': 'CustomizedNewProductSeriesList',
        'DEFINE_TAB': 'DefineTabList',
        'SCHEME_CENTER': 'SchemeRangeConfig',
        'PRODUCT_COMBINATION': 'ProductCombinationList',
        'SCHEME_CUSTOMIZATION': 'CustomizationRangeConfig'
      }
      if (com[type]) {
        this.dlgComponentName = com[type]
        this.visibleDlg = true
      }
    },
    dlgSelectSuccess(data) {
      const { gotoType } = this.formData
      let gotoValue = ''
      let gotoName = ''
      if (gotoType === 'HELP_CENTER_DETAIL') {
        gotoValue = data.id || ''
        gotoName = data.title || ''
      } else if (gotoType === 'GOODS_CENTER_DETAIL') {
        gotoValue = (data.spuId && data.id) ? `${data.spuId}|${data.id}` : ''
        gotoName = data.skuName || ''
      } else if (gotoType === 'CUSTOM_PAGE') {
        gotoValue = data.id || ''
        gotoName = data.name || ''
      } else if (this.formData.gotoType === 'CUSTOMIZED_NEW_PRODUCT_SERIES') {
        gotoValue = data.id || ''
        gotoName = data.seriesName || ''
      } else if (this.formData.gotoType === 'DEFINE_TAB') {
        gotoValue = data.id || ''
        gotoName = data.name || ''
      } else if (this.formData.gotoType === 'SCHEME_CENTER') {
        gotoValue = data.value || ''
        gotoName = data.name || ''
      } else if (this.formData.gotoType === 'SCHEME_CUSTOMIZATION') {
        gotoValue = data.value || ''
        gotoName = data.name || ''
      } else if (this.formData.gotoType === 'PRODUCT_COMBINATION') {
      // 搭配套餐id和name
        const names = []
        const ids = data.map(v => {
          names.push(v.name)
          return v.id
        })
        gotoValue = ids.join(',')
        gotoName = names.join(',')
      }
      this.$set(this.formData, 'gotoValue', gotoValue)
      this.$set(this.formData, 'gotoName', gotoName)
    },
    validate() {
      let flag = true
      const { gotoType, gotoValue, categoryDTOList, filterId, gotoName } = this.formData
      if (!gotoType) {
        return false
      }
      if (gotoType === 'GOODS_CENTER_CATEGORY') {
        flag = categoryDTOList && categoryDTOList.length > 0 && !!filterId
      } else if (['OUTSIDE_LINK', 'APPLY_PAGE'].includes(gotoType)) {
        flag = !!gotoValue
      } else if (['HELP_CENTER_DETAIL', 'GOODS_CENTER_DETAIL', 'CUSTOM_PAGE', 'SCHEME_CENTER', 'PRODUCT_COMBINATION', 'SCHEME_CUSTOMIZATION'].includes(gotoType)) {
        flag = !!gotoValue && !!gotoName
      }
      return flag
    }
  }
}

</script>
<style lang='scss' scoped>
.relate-category{
  display: flex;
  width: 100%;
  .relate-item{
    width: 33.33%;
    padding-right: 10px;
    box-sizing: border-box;
    &.clo-16{
      width: 66.666%;
    }
  }
  /deep/ .el-select{
    width: 100%;
  }
  /deep/ .el-cascader{
    .el-input__inner{
      // height: 28px !important;
    }
  }
}
</style>
